package com.zrrd.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.reggie.bean.Dish;
import com.zrrd.reggie.bean.Setmeal;
import com.zrrd.reggie.bean.SetmealDish;
import com.zrrd.reggie.bean.dto.SetmealDto;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.mapper.SetmealMapper;
import com.zrrd.reggie.service.SetmealDishService;
import com.zrrd.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Arrays;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    public void saveSetmealWithDish(SetmealDto dto) {
        this.save(dto);
        List<SetmealDish> setmealDishes = dto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(dto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    public SetmealDto getSetmealWithDish(Long id) {
        Setmeal setmeal = this.getById(id);
        SetmealDto dto=new SetmealDto();
        BeanUtils.copyProperties(setmeal,dto);
        QueryWrapper<SetmealDish> wrapper=new QueryWrapper<>();
        wrapper.eq("setmeal_id",id);
        List<SetmealDish> list = setmealDishService.list(wrapper);
        dto.setSetmealDishes(list);
        return dto;
    }

    @Override
    @Transactional
    public void updateSetmealWithDish(SetmealDto dto) {
        this.updateById(dto);
        QueryWrapper<SetmealDish> wrapper=new QueryWrapper<>();
        wrapper.eq("setmeal_id",dto.getId());
        setmealDishService.remove(wrapper);
        List<SetmealDish> setmealDishes = dto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(dto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);
    }


}
